package com.yiren.dbaa.module.practice_set.map.view.activity;

import android.app.AlertDialog;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.yiren.backstage.config.api.LoadConfigApi;
import com.yiren.backstage.config.bean.device.StationParamConfigBean;
import com.yiren.backstage.currency.bean.CarStateBean;
import com.yiren.backstage.currency.bean.GpsInfoBean;
import com.yiren.backstage.currency.bean.PointBean;
import com.yiren.backstage.currency.entity.TrajectoryEntity;
import com.yiren.backstage.currency.entity.TrajectoryPointEntity;
import com.yiren.backstage.currency.utils.GpsUtil;
import com.yiren.dbaa.R;
import com.yiren.dbaa.activity.BaseActivity;
import com.yiren.dbaa.constant.G;
import com.yiren.dbaa.currency.model.MultiLaneModel;
import com.yiren.dbaa.currency.model.RoadMarkModel;
import com.yiren.dbaa.module.practice_set.map.contract.CollectContract;
import com.yiren.dbaa.module.practice_set.map.presenter.CollectPresenter;
import com.yiren.dbaa.module.practice_set.map.view.adapter.AddRoadMarkAdapter;
import com.yiren.dbaa.module.practice_set.map.view.adapter.MultiLaneAdapter;
import com.yiren.dbaa.module.practice_set.map.view.adapter.RoadMarkAdapter;
import com.yiren.dbaa.module.practice_set.map.view.dialog.MapCollectDialog;
import com.yiren.dbaa.util.CarBitmapUtil;
import com.yiren.dbaa.util.DecimalTransferUtil;
import com.yiren.dbaa.util.DensityUtil;
import com.yiren.dbaa.util.GridViewUtil;
import com.yiren.dbaa.util.JtsUtils;
import com.yiren.dbaa.util.SystemBarUtil;
import com.yiren.dbaa.view.TrajectoryMapView;
import com.yiren.dbaa.view.adapter.collection.GridRadioGroup;
import com.yiren.dbaa.view.dialog.LoadDialog;
import com.yiren.dbaa.view.toast.MessageBox;

import org.apache.commons.lang.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @author lwb
 * @date : 2022/5/25 11:10
 * @description: 道路采集页面
 */
public class MapCollectActivity extends BaseActivity implements AdapterView.OnItemSelectedListener, MultiLaneAdapter.OnLaneClickListener,
        RadioGroup.OnCheckedChangeListener, CompoundButton.OnCheckedChangeListener, RoadMarkAdapter.OnMarkCollectClickListener, AddRoadMarkAdapter.OnRoadMarkActionListener {

    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_front_antenna)
    TextView tvFrontAntenna;
    @BindView(R.id.tv_back_antenna)
    TextView tvBackAntenna;
    @BindView(R.id.tv_current_lane)
    TextView tvCurrentLane;
    @BindView(R.id.tv_distance_line)
    TextView tvDistanceLine;
    @BindView(R.id.tv_east_coordinate)
    TextView tvEastCoordinate;
    @BindView(R.id.tv_north_coordinate)
    TextView tvNorthCoordinate;
    @BindView(R.id.tv_azimuth)
    TextView tvAzimuth;
    @BindView(R.id.rl_scqy)
    RelativeLayout rlScqy;   //刹车区域
    @BindView(R.id.tv_point_dis)
    TextView tvPointDis;     //距离上一点位距离
    @BindView(R.id.fl_surfaceView)
    FrameLayout flSurfaceView;
    @BindView(R.id.cb_show_map_number)
    CheckBox cbShowMapNumber;
    @BindView(R.id.cb_follow_location)
    CheckBox cbFollowLocation;
    @BindView(R.id.ll_traject_action)
    LinearLayout llTrajectAction;  //右侧操作布局
    @BindView(R.id.tv_project_name)
    TextView tvProjectName;
    @BindView(R.id.iv_select_traject)
    ImageView ivSelectTraject;
    @BindView(R.id.ll_line_type)
    LinearLayout llLineType;      //线路类型
    @BindView(R.id.rg_line_type)
    RadioGroup rgLineType;
    @BindView(R.id.rb_line_type1)
    RadioButton rbLineType1;
    @BindView(R.id.rb_line_type2)
    RadioButton rbLineType2;
    @BindView(R.id.rb_line_type3)
    RadioButton rbLineType3;
    @BindView(R.id.ll_width_color)
    LinearLayout llWidthColor;   //线宽和线色
    @BindView(R.id.ll_line_width)
    LinearLayout llLineWidth;    //线宽
    @BindView(R.id.et_line_width)
    EditText etLineWidth;
    @BindView(R.id.ll_line_color)
    LinearLayout llLineColor;    //线色
    @BindView(R.id.rg_line_color)
    RadioGroup rgLineColor;
    @BindView(R.id.rb_white)
    RadioButton rbWhite;
    @BindView(R.id.rb_yellow)
    RadioButton rbYellow;
    @BindView(R.id.ll_collect_dir)
    LinearLayout llCollectDir;  //采集方向
    @BindView(R.id.rg_collect_dir)
    RadioGroup rgCollectDir;
    @BindView(R.id.ll_yellow_dis)
    LinearLayout llYellowDis;   //中心线间距
    @BindView(R.id.et_yellow_dis)
    EditText etYellowDis;
    @BindView(R.id.ll_choose_traject)
    LinearLayout llChooseTraject; //选择修改的轨迹
    @BindView(R.id.btn_choose_traject)
    Button btnChooseTraject;
    @BindView(R.id.ll_choose_points)
    LinearLayout llChoosePoints;  //选择修改的点位
    @BindView(R.id.btn_choose_points)
    Button btnChoosePoints;
    @BindView(R.id.ll_one_row)
    LinearLayout llOneRow;       //按钮第一行
    @BindView(R.id.btn_point_1)
    Button btnPoint1;
    @BindView(R.id.btn_point_2)
    Button btnPoint2;
    @BindView(R.id.ll_two_row)
    LinearLayout llTwoRow;       //按钮第二行
    @BindView(R.id.btn_point_3)
    Button btnPoint3;
    @BindView(R.id.btn_point_4)
    Button btnPoint4;
    @BindView(R.id.lv_road_mark)
    ListView lvRoadMark;         //道路标识采集
    @BindView(R.id.ll_multi_lane)
    LinearLayout llMultiLane;    //多车道采集
    @BindView(R.id.sp_lane_count)
    Spinner spLaneCount;
    @BindView(R.id.lv_lane_set)
    ListView lvLaneSet;
    @BindView(R.id.btn_action_1)
    Button btnAction1;
    @BindView(R.id.btn_action_2)
    Button btnAction2;
    @BindView(R.id.tv_save_trajectory)
    TextView tvSaveTrajectory;
    @BindView(R.id.tv_change_traject)
    TextView tvChangeTraject;

    private MultiLaneAdapter multiLaneAdapter; //多车道适配器
    private Runnable stateInfoRunnable;        //状态信息线程类
    private Handler handler;   //状态信息发送handler
    private boolean isAutoCollect = false;     //是否自动采集
    private GpsInfoBean gpsInfo;
    private TrajectoryEntity currentTrajectory = null;   //当前轨迹
    public TrajectoryEntity currentUpdateTrajectory;     //当前修改轨迹
    public TrajectoryPointEntity currentUpdatePoint;     //当前修改轨迹点位
    private List<TrajectoryPointEntity> updateTrajectoryPoints;   //当前修改的轨迹点位集合
    public List<TrajectoryPointEntity> trajectoryPoints; //点位集合
    private PointBean lastAutoCollectPoint;        //最后一个自动采集点位
    private int collectType;   //采集类型
    private CollectContract.Presenter presenter;//轨迹采集操作实现
    private MapCollectDialog collectDialog;//轨迹采集对话框
    private TrajectoryMapView mapView;     //地图
    private StationParamConfigBean stationParamConfig;//固定站移动站主机盒参数配置
    private int changePosition = -1;   //临时记录位置
    private int position = -1;  //默认选择的项目
    private boolean isBaseCalibration;    //点位是否全部用标定的基站采集
    private JtsUtils jtsUtils;
    private RoadMarkAdapter roadMarkAdapter;   //道路标识适配器
    private List<RoadMarkModel> roadMarks;     //道路标识适配器填充数据
    private int currentMarkPosition = -1;      //当前采集的标识position
    private GridView gvSelectMark;     //选择的道路标识
    private List<Integer> roadMarkList;//道路标识list
    private AddRoadMarkAdapter selectRoadMarkAdapter; //新增道路标识适配器
    private List<Integer> markSelectList; //选择的道路标识

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_map_collect);
        ButterKnife.bind(this);
        SystemBarUtil.hideStatusBar(this);
        //非合伙人隐藏轨迹操作视图  道路标识
        if (!LoadConfigApi.loadUserParamConfig(this).isPartner()) {
            llTrajectAction.setVisibility(View.GONE);
        }
        initData();
        setData();
        initListener();
        refresh();
    }

    /**
     * 初始化数据
     */
    private void initData() {
        collectDialog = new MapCollectDialog(this);
        presenter = new CollectPresenter(this);
        handler = new Handler();
        jtsUtils = new JtsUtils();
        roadMarks = new ArrayList<>();
        roadMarkList = new ArrayList<>();
        markSelectList = new ArrayList<>();
        trajectoryPoints = new ArrayList<>();
        stationParamConfig = LoadConfigApi.loadStationParamConfig(this);
        isBaseCalibration = presenter.loadPointCalibrationStatus();
    }

    private void setData() {
        tvTitle.setText("轨迹采集");
        roadMarkList.clear();
        for (int i = 10; i <= 18; i++) {
            roadMarkList.add(i);
        }
        roadMarkList.add(21);
        cbFollowLocation.setText(cbFollowLocation.getText().toString() + ((isBaseCalibration && stationParamConfig.isBaseCalibration()) ? "新" : "老"));
    }

    private void initListener() {
        cbShowMapNumber.setOnCheckedChangeListener(this);
        cbFollowLocation.setOnCheckedChangeListener(this);
        rgLineType.setOnCheckedChangeListener(this);
        rgLineColor.setOnCheckedChangeListener(this);
        rgCollectDir.setOnCheckedChangeListener(this);
        spLaneCount.setOnItemSelectedListener(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mapView == null) {
            mapView = new TrajectoryMapView(this);
            ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
            mapView.setLayoutParams(params);
            mapView.setMapViewAttrs(true);
            mapView.setCollectInterface(true);
            mapView.setCurrentUpdateTrajectory(currentUpdateTrajectory);
            mapView.setCurrentUpdatePoint(currentUpdatePoint);
            mapView.setShowBsPoint(cbShowMapNumber.isChecked());
            if (trajectoryPoints != null) {
                mapView.trajectoryPoints = new ArrayList<TrajectoryPointEntity>();
                mapView.trajectoryPoints.addAll(trajectoryPoints);
            }
            if (currentTrajectory != null) {
                mapView.setCollect(true);
                mapView.collectType = collectType;
            }
        } else {
            mapView.startThread();
        }
        flSurfaceView.removeAllViews();
        flSurfaceView.addView(mapView);
        mapView.setBitmap(CarBitmapUtil.getBitmap(this, CarBitmapUtil.CAR_NORMAL));
        mapView.setOnMapViewDragListener((currentText) -> {
            updateTrajectoryPoints = mapView.allMap100.get(currentUpdateTrajectory.getId());
            if (null != currentUpdatePoint && !"0".equals(currentText)) {
                btnChoosePoints.setText(currentText);
            }
        });
    }

    /**
     * 界面坐标刷新
     */
    private void refresh() {
        stateInfoRunnable = new Runnable() {
            @Override
            public void run() {
                gpsInfo = GpsInfoBean.getInstance();
                if (null != gpsInfo) {
                    tvFrontAntenna.setText("前天线:" + gpsInfo.getStatusDirection() + "/" + gpsInfo.getSatelliteFront());
                    tvBackAntenna.setText("后天线:" + gpsInfo.getStatusPosition() + "/" + gpsInfo.getSatelliteBack());
                    tvCurrentLane.setText("当前车道:" + CarStateBean.getInstance().getTravelVehicleLane());
                    tvDistanceLine.setText("距离边线:" + (Math.abs(CarStateBean.getInstance().getRightFrontDistance()) > 400 ? 999900 : CarStateBean.getInstance().getRightFrontDistance()) + "," + (Math.abs(CarStateBean.getInstance().getRightBackDistance()) > 400 ? 999900 : CarStateBean.getInstance().getRightBackDistance()));
                    tvEastCoordinate.setText("东坐标:" + gpsInfo.getDistanceX());
                    tvNorthCoordinate.setText("北坐标:" + gpsInfo.getDistanceY());
                    tvAzimuth.setText("方位角:" + gpsInfo.getAzimuth());
                    //textSatelliteBack.setText("后溜距离:" +G.getCarState().getBackSkateDistance());
                    if (isAutoCollect) {
                        lastAutoCollectPoint = presenter.autoCollectPoint(lastAutoCollectPoint, currentTrajectory, mapView);
                    }
                    if (tvPointDis.getVisibility() == View.VISIBLE && mapView != null && mapView.trajectoryPoints.size() > 0) {
                        PointBean point = mapView.trajectoryPoints.get(mapView.trajectoryPoints.size() - 1).getPoint();
                        double distance;
                        if (isBaseCalibration && stationParamConfig.isBaseCalibration()) {
                            distance = GpsUtil.getDistanceGpsPoint(gpsInfo, point, stationParamConfig);
                        } else {
                            distance = Math.sqrt(Math.pow((gpsInfo.getDistanceX() - point.getX()), 2) + Math.pow((gpsInfo.getDistanceY() - point.getY()), 2));
                        }
                        tvPointDis.setText("距离上一点位距离: " + DecimalTransferUtil.formatMeter(distance) + "M");
                    }
                }
                if (null != mapView) {
                    currentUpdateTrajectory = mapView.getCurrentUpdateTrajectory();
                    currentUpdatePoint = mapView.getCurrentUpdatePoint();
                    collectType = mapView.collectType;
                    if (null != mapView.trajectoryPoints) {
                        trajectoryPoints = mapView.trajectoryPoints;
                        if (null != gpsInfo && mapView.trajectoryPoints.size() > 0 && mapView.isCollect()) {
                            PointBean point = mapView.trajectoryPoints.get(mapView.trajectoryPoints.size() - 1).getPoint();
                            double distance;
                            if (isBaseCalibration && stationParamConfig.isBaseCalibration()) {
                                distance = GpsUtil.getDistanceGpsPoint(gpsInfo, point, stationParamConfig);
                            } else {
                                distance = Math.sqrt(Math.pow((gpsInfo.getDistanceX() - point.getX()), 2) + Math.pow((gpsInfo.getDistanceY() - point.getY()), 2));
                            }
                            tvPointDis.setVisibility(View.VISIBLE);
                            tvPointDis.setText("距离上一点位距离: " + DecimalTransferUtil.formatMeter(distance) + "M");
                        } else {
                            tvPointDis.setVisibility(View.GONE);
                        }
                    }
                }
                handler.postDelayed(this, 100);
            }
        };
        stateInfoRunnable.run();
    }


    /**
     * 点击事件
     *
     * @param v
     */
    @OnClick({R.id.iv_back, R.id.iv_map_up, R.id.iv_map_down, R.id.ll_traject_type, R.id.btn_choose_traject, R.id.btn_choose_points,
            R.id.btn_point_1, R.id.btn_point_2, R.id.btn_point_3, R.id.btn_point_4, R.id.btn_action_1, R.id.btn_action_2, R.id.tv_change_traject, R.id.tv_save_trajectory})
    public void onViewClicked(View v) {
        switch (v.getId()) {
            case R.id.iv_back:   //返回
                if (null != mapView && mapView.isCollect()) {
                    MessageBox.show(this, "当前轨迹尚未采集结束！");
                    return;
                }
                finish();
                break;
            case R.id.iv_map_up://放大
                if (null != mapView) mapView.setAccuracy(false);
                break;
            case R.id.iv_map_down: //缩小
                if (null != mapView) mapView.setAccuracy(true);
                break;
            case R.id.ll_traject_type: //轨迹类型
                if (ivSelectTraject.getVisibility() == View.VISIBLE) {
                    if (null != mapView && mapView.isCollect() && null != currentTrajectory) {
                        MessageBox.show(this, "当前轨迹尚未采集完成！");
                        return;
                    } else {
                        showTrajectoryTypeDialog();
                    }
                }
                break;
            case R.id.btn_choose_traject: //选择修改的轨迹
                if (null != currentTrajectory) {
                    changeTrajectory(1);
                }
                showTrajectoryDialog();
                break;
            case R.id.btn_choose_points: //选择修改的点
                showTrajectoryPointDialog();
                break;
            case R.id.btn_point_1://按钮1
                if (position == -1) {  //删除点位
                    if (null != mapView.getCurrentUpdatePoint()) {
                        int trajectoryType = mapView.getCurrentUpdatePoint().getTrajectory().getTrajectoryType();
                        if (trajectoryType == 3 || trajectoryType == 4 || trajectoryType == 6 || trajectoryType >= 10 && trajectoryType <= 18) {
                            MessageBox.show(this, "当前轨迹点位不可删除！");
                            return;
                        }
                        collectDialog.doDeleteCustom(new MapCollectDialog.OnCollectDialogListener() {
                            @Override
                            public void onDialogSure() {
                                if (presenter.deleteTrajectoryPoint(mapView.getCurrentUpdatePoint())) {
                                    updateTrajectoryPoints.remove(mapView.getCurrentUpdatePoint());
                                    mapView.setCurrentUpdatePoint(null);
                                    btnChoosePoints.setText("");
                                    MessageBox.show(MapCollectActivity.this, "删除点位成功");
                                }
                            }
                        });
                    } else {
                        MessageBox.show(this, "请先选择删除的点位！");
                    }
                } else {//采集点位
                    if (noEnoughAccuracy()) return;
                    if (position == 0 || position == 1) {
                        if (isAutoCollect) {
                            MessageBox.show(this, "请先结束自动采集！");
                            return;
                        }
                        if (mapView.isCollect()) {
                            doCollectPoint(1);
                        } else {
                            MessageBox.show(this, "当前轨迹已采集结束！");
                            return;
                        }
                    } else if (position == 7 || position == 8) {
                        doCollectPoint(1);
                    } else if (position == 3 || position == 4 || position == 5 || position == 9) {
                        if (mapView.trajectoryPoints.size() >= 1) { //校准
                            presenter.calibrationTrajectoryPoint(mapView.trajectoryPoints.get(0), gpsInfo);
                            setScqyPoint4();
                        } else { //采集
                            doCollectPoint(1);
                        }
                    }
                }
                break;
            case R.id.btn_point_2://按钮2
                if (noEnoughAccuracy()) return;
                if (position == -1) { //校准点位
                    if (null != mapView.getCurrentUpdatePoint()) {
                        presenter.calibrationTrajectoryPoint(mapView.getCurrentUpdatePoint(), gpsInfo);
                    } else {
                        MessageBox.show(this, "请先选择校准的点位！");
                    }
                } else {
                    if (position == 0) {
                        if (mapView.trajectoryPoints.size() > 0) {
                            presenter.calibrationTrajectoryPoint(mapView.trajectoryPoints.get(mapView.trajectoryPoints.size() - 1), gpsInfo);
                        }
                    } else if (position == 1) {
                        if (mapView.trajectoryPoints.size() > 0) {
                            presenter.calibrationTrajectoryPoint(mapView.trajectoryPoints.get(mapView.trajectoryPoints.size() - 1), gpsInfo);
                        }
                    } else if (position == 3 || position == 4 || position == 5 || position == 9) { //采集或校准
                        if (mapView.trajectoryPoints.size() >= 2) { //校准
                            presenter.calibrationTrajectoryPoint(mapView.trajectoryPoints.get(1), gpsInfo);
                            setScqyPoint4();
                        } else { //采集
                            if (mapView.trajectoryPoints.size() == 0) {
                                MessageBox.show(this, "请先采集点位1");
                                return;
                            }
                            doCollectPoint(2);
                        }
                    } else {
                        MessageBox.show(this, "请先采集点位！");
                    }
                }
                break;
            case R.id.btn_point_3://按钮3
                if (noEnoughAccuracy()) return;
                if (position == 0 || position == 1) {
                    if (mapView.trajectoryPoints.size() == 0) {
                        MessageBox.show(this, "当前轨迹少于一个点，不可结束！");
                        return;
                    }
                    if (!mapView.isCollect()) {
                        MessageBox.show(this, "当前轨迹已经采集结束！");
                        return;
                    }
                    doCollectPoint(3);
                } else if (position == 3 || position == 9) {  //人行横道线或刹车区域
                    if (mapView.trajectoryPoints.size() < 2) {
                        MessageBox.show(this, "请先采集完前两个点位！");
                    } else if (mapView.trajectoryPoints.size() == 2) { //采集
                        doCollectPoint(3);
                    } else {  //校准
                        presenter.calibrationTrajectoryPoint(mapView.trajectoryPoints.get(2), gpsInfo);
                        setScqyPoint4();
                    }
                }
                break;
            case R.id.btn_point_4://按钮4
                if (noEnoughAccuracy()) return;
                if (position == 0 || position == 1) {
                    if (null == mapView.trajectoryPoints || mapView.trajectoryPoints.size() == 0) {
                        MessageBox.show(this, "请先采集第一个点位！");
                        return;
                    }
                    if (!mapView.isCollect()) {
                        MessageBox.show(this, "当前线段已采集结束！");
                        return;
                    }
                    isAutoCollect = !isAutoCollect;
                    if (isAutoCollect) {
                        btnPoint4.setText("结束自动采集");
                    } else {
                        btnPoint4.setText("开始自动采集");
                        lastAutoCollectPoint = null;
                    }
                } else if (position == 3) {
                    if (mapView.trajectoryPoints.size() < 3) {
                        MessageBox.show(this, "请先采集前面的点位！");
                    } else if (mapView.trajectoryPoints.size() == 3) {
                        doCollectPoint(4);
                    } else if (mapView.trajectoryPoints.size() == 4) {
                        presenter.calibrationTrajectoryPoint(mapView.trajectoryPoints.get(3), gpsInfo);
                    }
                }
                break;
            case R.id.btn_action_1:
                if (position == 2) {  //校准当前轨迹
                    if (null == mapView.laneLists || mapView.laneLists.size() == 0) {
                        MessageBox.show(this, "尚未采集点位！");
                        return;
                    }
                    if (noEnoughAccuracy()) return;
                    List<TrajectoryPointEntity> trajectoryPoints = mapView.laneLists.get(changePosition).getTrajectoryPoints();
                    if (null == trajectoryPoints || trajectoryPoints.size() == 0) {
                        MessageBox.show(this, "当前点位为空！");
                        return;
                    }
                    if (presenter.calibrationTrajectoryPoint(trajectoryPoints.get(trajectoryPoints.size() - 1), gpsInfo)) {
                        multiLaneAdapter.notifyDataSetChanged();
                    }
                } else if (position == 6) { //新增采集标识
                    if (null != currentTrajectory && mapView.trajectoryPoints.size() < 2) {
                        MessageBox.show(this, "当前标识未采集完成,请继续采集！");
                        return;
                    }
                    showAddRoadMarkDialog();
                } else {
                    //删除上一点位
                    if (mapView.trajectoryPoints.size() > 0) {
                        TrajectoryPointEntity tp = mapView.trajectoryPoints.get(mapView.trajectoryPoints.size() - 1);
                        if (presenter.deleteTrajectoryPoint(tp)) {
                            mapView.trajectoryPoints.remove(mapView.trajectoryPoints.size() - 1);
                            if (position == 0 || position == 1 && mapView.isCollect()) {
                                btnPoint1.setText("采点" + (mapView.trajectoryPoints.size() + 1));
                            } else if (position == 7 || position == 8) {
                                if (mapView.trajectoryPoints.size() == 0) {
                                    btnPoint1.setText("采集点位");
                                } else {
                                    btnPoint1.setText("采集点位" + (mapView.trajectoryPoints.size() + 1));
                                }
                            }
                            MessageBox.show(this, "删除点位成功");
                        }
                    } else {
                        MessageBox.show(this, "没有可删除的点位");
                    }
                }
                break;
            case R.id.btn_action_2:
                if (position == 6) {
                    if (roadMarks.size() > 0) {
                        if (mapView.isCollect()) {
                            MessageBox.show(this, "正在采集中，不可删除！");
                            return;
                        } else {
                            collectDialog.doDeleteCustom(new MapCollectDialog.OnCollectDialogListener() {
                                @Override
                                public void onDialogSure() {
                                    TrajectoryEntity trajectory = roadMarks.get(roadMarks.size() - 1).getTrajectory();
                                    if (presenter.deleteTrajectory(trajectory)) {
                                        MessageBox.show(MapCollectActivity.this, "删除轨迹成功");
                                        if (currentMarkPosition == roadMarks.size() - 1) {
                                            mapView.setCollect(false);
                                        }
                                        roadMarks.remove(roadMarks.size() - 1);
                                        currentMarkPosition = -1;
                                        roadMarkAdapter.notifyDataSetChanged();
                                        if (roadMarks.size() == 0) {
                                            initContent();
                                        }
                                    }
                                }
                            });
                        }
                    }
                } else {
                    if (null != currentTrajectory) {
                        collectDialog.doDeleteCustom(new MapCollectDialog.OnCollectDialogListener() {
                            @Override
                            public void onDialogSure() {
                                if (presenter.deleteTrajectory(currentTrajectory)) {
                                    MessageBox.show(MapCollectActivity.this, "删除轨迹成功");
                                    initContent();
                                }
                            }
                        });
                    } else {
                        MessageBox.show(this, "当前轨迹为空！");
                    }
                }
                break;
            case R.id.tv_change_traject:
                if (position == -1) {  //修改属性
                    if (null != currentTrajectory) {
                        changeTrajectory(2);
                    } else {
                        MessageBox.show(this, "当前轨迹为空！");
                    }
                } else if (position == 2) { //多车道
                    if (null != mapView.laneLists && mapView.laneLists.size() > 0) {
                        MessageBox.show(this, "当前轨迹尚未采集完成！");
                    } else {
                        initContent();
                    }
                } else if (position == 7 || position == 8) {
                    if (null != currentTrajectory && mapView.trajectoryPoints.size() < 4) {
                        MessageBox.show(this, "当前轨迹尚未采集完成！");
                        return;
                    }
                    initContent();
                } else {
                    if (null != currentTrajectory && mapView.isCollect()) {
                        MessageBox.show(this, "当前轨迹尚未采集完成！");
                        return;
                    }
                    initContent();
                }
                break;
            case R.id.tv_save_trajectory:
                if (position == -1) {  //采集轨迹
                    if (null != currentTrajectory) {
                        MessageBox.show(this, "请先完成当前轨迹修改！");
                        return;
                    }
                    //调用接口基站是否标定过
                    collectDialog.showChangeDeviceDialog(new MapCollectDialog.OnCollectDialogListener() {
                        @Override
                        public void onDialogSure() {
                            showTrajectoryTypeDialog();
                        }
                    });
                } else if (position == 2) { //多车道保存
                    if (null == mapView.laneLists || mapView.laneLists.size() == 0) {
                        MessageBox.show(this, "请先采集车道！");
                        return;
                    }
                    presenter.multiLaneTrajectorySave(mapView);
                    initContent();
                }
                break;
        }
    }

    /***
     * 多车道选择点击监控
     */
    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        switch (parent.getId()) {
            case R.id.sp_lane_count: //多车道采集车道数量
                if (position == 0) {
                } else {
                    mapView.laneLists = new ArrayList<>();
                    for (int i = 0; i <= position; i++) {
                        TrajectoryEntity trajectory = presenter.saveTrajectory(1, true);
                        if (null != trajectory) {
                            MultiLaneModel model = new MultiLaneModel();
                            model.setNumber(i + 1);
                            model.setShowNumber(true);
                            model.setLineType(1);
                            model.setLineColor(1);
                            model.setLineWidth(15);
                            model.setAdd(true);
                            model.setDelete(false);
                            model.setTrajectory(trajectory);
                            model.setTrajectoryPoints(new ArrayList<TrajectoryPointEntity>());
                            model.setCollectEnd(false);
                            mapView.laneLists.add(model);
                        }
                    }
                    multiLaneAdapter = new MultiLaneAdapter(this, mapView.laneLists, this);
                    lvLaneSet.setAdapter(multiLaneAdapter);
                }
                break;
        }
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {
    }

    /**
     * RadioGroup点击事件监听
     *
     * @param group
     * @param checkedId
     */
    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        switch (group.getId()) {
            case R.id.rg_line_type: //实、虚、起步靠边实线、双簧线
                if (null != currentTrajectory) {
                    if (currentTrajectory.getTrajectoryType() == 1 || currentTrajectory.getTrajectoryType() == 2 || currentTrajectory.getTrajectoryType() == 7) {
                        switch (checkedId) {
                            case R.id.rb_line_type1:  //实线
                                mapView.collectType = TrajectoryEntity.getTrajectoryType("实线");
                                break;
                            case R.id.rb_line_type2:  //虚线
                                mapView.collectType = TrajectoryEntity.getTrajectoryType("虚线");
                                break;
                            case R.id.rb_line_type3: //起步靠边实线
                                mapView.collectType = TrajectoryEntity.getTrajectoryType("起步靠边实线");
                                break;
                        }
                    } else if (currentTrajectory.getTrajectoryType() == 9 || currentTrajectory.getTrajectoryType() == 19 || currentTrajectory.getTrajectoryType() == 20) {
                        switch (checkedId) {
                            case R.id.rb_line_type1:  //双实线
                                mapView.collectType = TrajectoryEntity.getTrajectoryType("双实线");
                                break;
                            case R.id.rb_line_type2:  //双虚线
                                mapView.collectType = TrajectoryEntity.getTrajectoryType("双虚线");
                                break;
                            case R.id.rb_line_type3:  //虚实线
                                mapView.collectType = TrajectoryEntity.getTrajectoryType("虚实线");
                                break;
                        }
                    }
                    currentTrajectory.setTrajectoryType(mapView.collectType);
                    presenter.updateTrajectory(currentTrajectory);
                }
                break;
            case R.id.rg_line_color: //线色
                int color = 0;
                switch (checkedId) {
                    case R.id.rb_white:
                        color = 1;
                        break;
                    case R.id.rb_yellow:
                        color = 2;
                        break;
                }
                if (null != currentTrajectory && color != 0) {
                    currentTrajectory.setLineColor(color);
                    presenter.updateTrajectory(currentTrajectory);
                }
                break;
            case R.id.rg_collect_dir: //采集方向
                int collectDirection = 0;
                switch (checkedId) {
                    case R.id.rb_zx:
                        collectDirection = 1;
                        break;
                    case R.id.rb_nx:
                        collectDirection = 2;
                        break;
                }
                if (null != currentTrajectory && collectDirection != 0) {
                    currentTrajectory.setCollectDirection(collectDirection);
                    presenter.updateTrajectory(currentTrajectory);
                }
                break;
            case R.id.rg_road_mark: //道路标识
                switch (checkedId) {
                    case R.id.rb_lkzx:
                        mapView.collectType = 10;
                        break;
                    case R.id.rb_lkyz:
                        mapView.collectType = 11;
                        break;
                    case R.id.rb_lkzz:
                        mapView.collectType = 12;
                        break;
                    case R.id.rb_lkdt:
                        mapView.collectType = 13;
                        break;
                    case R.id.rb_lkzxzz:
                        mapView.collectType = 14;
                        break;
                    case R.id.rb_lkzxyz:
                        mapView.collectType = 15;
                        break;
                    case R.id.rb_lkzxdt:
                        mapView.collectType = 16;
                        break;
                    case R.id.rb_lkzzdt:
                        mapView.collectType = 17;
                        break;
                    case R.id.rb_lkzxzzdt:
                        mapView.collectType = 18;
                        break;
                    case R.id.rb_lkzyz:
                        mapView.collectType = 21;
                        break;
                }
                break;
        }

    }

    /**
     * 轨迹图点击事件回调
     *
     * @param buttonView
     * @param isChecked
     */
    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (buttonView == cbShowMapNumber) {  //显示地图编号
            mapView.setShowBsPoint(isChecked);
        } else if (buttonView == cbFollowLocation) { //跟随定位
            mapView.setGsdw(isChecked);
            if (isChecked) {
                mapView.setUpLocation(false);
            }
        }
    }

    /**
     * 采集轨迹选择弹出框
     */
    private void showTrajectoryTypeDialog() {
        changePosition = 0;
        HashMap<Integer, String> map = TrajectoryEntity.getTrajectoryCollectType();
        final String[] items = new String[map.size()];
        for (int i = 0; i < map.size(); i++) {
            items[i] = map.get(i);
        }
        AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this);
        alertBuilder.setTitle("请选择采集轨迹类型");
        alertBuilder.setSingleChoiceItems(items, 0, (dialog, i) -> changePosition = i);
        alertBuilder.setPositiveButton("取消", (dialog, which) -> dialog.dismiss());
        alertBuilder.setNegativeButton("确定", (dialog, which) -> {
            position = changePosition;
            tvChangeTraject.setText("修改轨迹");
            setViewVisibility(rlScqy, position == 9 ? 1 : 3);
            setViewVisibility(tvPointDis, position == 9 ? 1 : 3);
            //新增车辆轨迹
            switch (position) {
                case 0:
                    rbLineType1.setChecked(true);
                    mapView.collectType = TrajectoryEntity.getTrajectoryType("实线");
                    break;
                case 1:
                    rbLineType1.setChecked(true);
                    mapView.collectType = TrajectoryEntity.getTrajectoryType("双实线");
                    break;
                case 2:
                    mapView.collectType = TrajectoryEntity.getTrajectoryType("多车道采集");
                    break;
                case 3:
                    mapView.collectType = TrajectoryEntity.getTrajectoryType("人行横道线");
                    break;
                case 4:
                    mapView.collectType = TrajectoryEntity.getTrajectoryType("停止线");
                    break;
                case 5:
                    mapView.collectType = TrajectoryEntity.getTrajectoryType("中心圈");
                    break;
                case 7:
                    mapView.collectType = TrajectoryEntity.getTrajectoryType("网状线");
                    break;
                case 8:
                    mapView.collectType = TrajectoryEntity.getTrajectoryType("禁止停车区域");
                    break;
                case 9:
                    mapView.collectType = TrajectoryEntity.getTrajectoryType("刹车区域");
                    break;
                default:
                    break;
            }
            if (position == 2) {  //多车道
                mapView.laneLists = new ArrayList<>();
                tvProjectName.setText(items[position]);
                setViewVisibility(ivSelectTraject, 1);
                presenter.initTrajectoryPoints(mapView);
                setViewVisibility(llMultiLane, 1);
                initMultiLane();
            } else if (position == 6) {//道路标识
                tvProjectName.setText(items[position]);
                setViewVisibility(ivSelectTraject, 1);
                presenter.initTrajectoryPoints(mapView);
                setViewVisibility(llMultiLane, 3);
                initLineOrMark();
            } else {
                currentTrajectory = presenter.saveTrajectory(mapView.collectType, true);
                if (null == currentTrajectory) {
                    MessageBox.show(this, "采集轨迹失败！");
                } else {
                    mapView.setCollect(true);
                    tvProjectName.setText(items[position]);
                    setViewVisibility(ivSelectTraject, 1);
                    presenter.initTrajectoryPoints(mapView);
                    setViewVisibility(llMultiLane, 3);
                    initLineOrMark();
                }
            }
            dialog.dismiss();
        });
        alertBuilder.create().show();
    }

    /**
     * 修改轨迹选择弹出框
     */
    private void showTrajectoryDialog() {
        if (null == mapView.allMap100 || mapView.allMap100.size() == 0) {
            MessageBox.show(this, "附近没有轨迹，请开往轨迹修改区域！");
            return;
        }
        changePosition = 0;
        final String[] items = new String[mapView.allMap100.size()];
        final String[] trajectId = new String[mapView.allMap100.size()];
        Iterator<Map.Entry<String, List<TrajectoryPointEntity>>> it = mapView.allMap100.entrySet().iterator();
        int index = 0;
        while (it.hasNext()) {
            Map.Entry m = (Map.Entry) it.next();
            List<TrajectoryPointEntity> trajectoryPoints = (List<TrajectoryPointEntity>) m.getValue();
            if (null != trajectoryPoints && trajectoryPoints.size() > 0) {
                items[index] = "地图编号：" + (index + 1) + "(" + TrajectoryEntity.getTrajectoryTypes().get(trajectoryPoints.get(0).getTrajectory().getTrajectoryType()) + ")";
                trajectId[index] = (String) m.getKey();
                index++;
            }
        }
        AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this);
        alertBuilder.setTitle("请选择修改的轨迹");
        alertBuilder.setSingleChoiceItems(items, 0, (dialog, i) -> changePosition = i);
        alertBuilder.setPositiveButton("取消", (dialog, which) -> dialog.dismiss());
        alertBuilder.setNegativeButton("确定", (dialog, which) -> {
            btnChooseTraject.setText(items[changePosition]);
            mapView.setCurrentUpdatePoint(null);
            updateTrajectoryPoints = mapView.allMap100.get(trajectId[changePosition]);
            if (null != updateTrajectoryPoints) {
                mapView.setCurrentUpdateTrajectory(updateTrajectoryPoints.get(0).getTrajectory());
                currentTrajectory = updateTrajectoryPoints.get(0).getTrajectory();
                if (currentTrajectory.getTrajectoryType() == 1 || currentTrajectory.getTrajectoryType() == 2 || currentTrajectory.getTrajectoryType() == 7) {
                    setViewVisibility(llLineType, 1);
                    rbLineType1.setText("实线");
                    rbLineType2.setText("虚线");
                    rbLineType3.setText("起步靠边实线");
                    if (currentTrajectory.getTrajectoryType() == 1) {
                        rbLineType1.setChecked(true);
                    } else if (currentTrajectory.getTrajectoryType() == 2) {
                        rbLineType2.setChecked(true);
                    } else {
                        rbLineType3.setChecked(true);
                    }
                    setViewVisibility(llCollectDir, 1);
                } else if (currentTrajectory.getTrajectoryType() == 9 || currentTrajectory.getTrajectoryType() == 19 || currentTrajectory.getTrajectoryType() == 0 || currentTrajectory.getTrajectoryType() == 20) {
                    setViewVisibility(llLineType, 1);
                    rbLineType1.setText("双实线");
                    rbLineType2.setText("双虚线");
                    rbLineType3.setText("虚实线");
                    if (currentTrajectory.getTrajectoryType() == 9) {
                        rbLineType1.setChecked(true);
                    } else if (currentTrajectory.getTrajectoryType() == 19) {
                        rbLineType2.setChecked(true);
                    } else {
                        rbLineType3.setChecked(true);
                    }
                    setViewVisibility(llCollectDir, 3);
                } else {
                    setViewVisibility(llCollectDir, 3);
                }
                etLineWidth.setText(currentTrajectory.getLineWidth() + "");
                if (currentTrajectory.getLineColor() == 1) {
                    ((RadioButton) rgLineColor.getChildAt(0)).setChecked(true);
                } else {
                    ((RadioButton) rgLineColor.getChildAt(1)).setChecked(true);
                }
                if (currentTrajectory.getCollectDirection() == 2) {
                    ((RadioButton) rgCollectDir.getChildAt(1)).setChecked(true);
                } else {
                    ((RadioButton) rgCollectDir.getChildAt(0)).setChecked(true);
                }
                btnChoosePoints.setText("");
            } else {
                MessageBox.show(this, "当前选择的轨迹点位为空！");
            }
            dialog.dismiss();
        });
        alertBuilder.create().show();
    }

    /**
     * 修改轨迹点位选择弹出框
     */
    private void showTrajectoryPointDialog() {
        changePosition = 0;
        if (null == mapView.getCurrentUpdateTrajectory() || null == updateTrajectoryPoints || updateTrajectoryPoints.size() == 0) {
            MessageBox.show(this, "请先选择需要修改的轨迹！");
            return;
        }
        final String[] items = new String[updateTrajectoryPoints.size()];
        for (int i = 0; i < updateTrajectoryPoints.size(); i++) {
            items[i] = (i + 1) + "";
        }
        AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this);
        alertBuilder.setTitle("请选择当前轨迹修改的点位");
        alertBuilder.setSingleChoiceItems(items, 0, (dialog, i) -> changePosition = i);
        alertBuilder.setPositiveButton("取消", (dialog, which) -> dialog.dismiss());
        alertBuilder.setNegativeButton("确定", (dialog, which) -> {
            mapView.setCurrentUpdatePoint(updateTrajectoryPoints.get(changePosition));
            btnChoosePoints.setText(items[changePosition]);
            dialog.dismiss();
        });
        alertBuilder.create().show();
    }

    /**
     * 新增道路标识弹出框
     */
    private void showAddRoadMarkDialog() {
        AlertDialog roadMarkDialog = new AlertDialog.Builder(this).create();
        roadMarkDialog.setCancelable(false);
        roadMarkDialog.show();
        WindowManager.LayoutParams params = roadMarkDialog.getWindow().getAttributes();
        params.width = (DensityUtil.getScreenWidth(this) * 7) / 10;
        params.height = (DensityUtil.getScreenHeight(this) * 8) / 10;
        roadMarkDialog.getWindow().setAttributes(params);
        Window window = roadMarkDialog.getWindow();
        window.setContentView(R.layout.dialog_add_road_mark);
        gvSelectMark = (GridView) window.findViewById(R.id.gv_select_mark);
        GridView gvRoadMark = (GridView) window.findViewById(R.id.gv_road_mark);
        TextView tvMarkCancel = (TextView) window.findViewById(R.id.tv_mark_cancel);
        TextView tvMarkSure = (TextView) window.findViewById(R.id.tv_mark_sure);
        AddRoadMarkAdapter addRoadMarkAdapter = new AddRoadMarkAdapter(this, 1, roadMarkList, this);
        gvRoadMark.setAdapter(addRoadMarkAdapter);
        selectRoadMarkAdapter = new AddRoadMarkAdapter(this, 2, markSelectList, this);
        gvSelectMark.setAdapter(selectRoadMarkAdapter);
        tvMarkCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (roadMarkDialog != null && roadMarkDialog.isShowing()) {
                    markSelectList.clear();
                    roadMarkDialog.dismiss();
                }
            }
        });
        tvMarkSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                for (int i = 0; i < markSelectList.size(); i++) {
                    TrajectoryEntity trajectory = presenter.saveTrajectory(markSelectList.get(i), true);
                    RoadMarkModel model = new RoadMarkModel();
                    model.setMarkType(markSelectList.get(i));
                    model.setPoint1Type(1);
                    model.setPoint2Type(1);
                    model.setTrajectory(trajectory);
                    roadMarks.add(model);
                }
                roadMarkAdapter.notifyDataSetChanged();
                if (roadMarkDialog != null && roadMarkDialog.isShowing()) {
                    markSelectList.clear();
                    roadMarkDialog.dismiss();
                }
            }
        });
    }

    /**
     * 修改道路标识类型弹出框
     */
    private void showChangeRoadMarkDialog(int markType, final int position) {
        AlertDialog changeMarkDialog = new AlertDialog.Builder(this).create();
        changeMarkDialog.setCancelable(false);
        changeMarkDialog.show();
        // 高度占了全屏，临时给了一个高度，代码未优化
        WindowManager.LayoutParams params = changeMarkDialog.getWindow().getAttributes();
        params.width = (DensityUtil.getScreenWidth(this) * 6) / 10;
        changeMarkDialog.getWindow().setAttributes(params);
        Window window = changeMarkDialog.getWindow();
        window.setContentView(R.layout.dialog_change_road_mark);
        GridRadioGroup rgRoadMark = (GridRadioGroup) window.findViewById(R.id.rg_road_mark);
        TextView tvChangeCancel = (TextView) window.findViewById(R.id.tv_change_cancel);
        TextView tvChangeSure = (TextView) window.findViewById(R.id.tv_change_sure);
        rgRoadMark.setOnCheckedChangeListener(this);
        int childCount = rgRoadMark.getChildCount();
        for (int i = 0; i < childCount; i++) {
            if (rgRoadMark.getChildAt(i).getTag().equals(markType + "")) {
                ((RadioButton) rgRoadMark.getChildAt(i)).setChecked(true);
            }
        }
        tvChangeCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (changeMarkDialog != null && changeMarkDialog.isShowing()) {
                    changeMarkDialog.dismiss();
                }
            }
        });
        tvChangeSure.setOnClickListener(v -> {
            TrajectoryEntity trajectory = roadMarks.get(position).getTrajectory();
            trajectory.setTrajectoryType(mapView.collectType);
            if (presenter.updateTrajectory(trajectory)) {
                roadMarks.get(position).setMarkType(mapView.collectType);
                roadMarkAdapter.notifyDataSetChanged();
            }
            if (changeMarkDialog != null && changeMarkDialog.isShowing()) {
                changeMarkDialog.dismiss();
            }
        });
    }


    /**
     * 非多车道初始化
     */
    private void initLineOrMark() {
        setViewVisibility(tvSaveTrajectory, 3);
        setViewVisibility(llChooseTraject, 3);
        setViewVisibility(llChoosePoints, 3);
        setViewVisibility(llLineType, 3);
        setViewVisibility(llLineWidth, 1);
        setViewVisibility(llCollectDir, 3);
        setViewVisibility(llYellowDis, 3);
        setViewVisibility(llOneRow, 1);
        setViewVisibility(llTwoRow, 3);
        if (position == 0 || position == 1) {
            setViewVisibility(llLineType, 1);
            rbLineType1.setChecked(true);
            etLineWidth.setText("15");
            setViewVisibility(llLineColor, 1);
            rbWhite.setChecked(true);
            setViewVisibility(llCollectDir, 1);
            setViewVisibility(llTwoRow, 1);
            setButtonBackground(btnPoint1, "采点1", 1);
            setButtonBackground(btnPoint2, "校准当前点位", 1);
            setButtonBackground(btnPoint3, "采集线段终点", 1);
            setButtonBackground(btnPoint4, "开始自动采集", 1);
            setButtonBackground(btnAction1, "删除上一点位", 2);
            setButtonBackground(btnAction2, "删除当前线段", 2);
            if (position == 0) {
                rbLineType1.setText("实线");
                rbLineType2.setText("虚线");
                rbLineType3.setText("起步靠边实线");
                mapView.collectType = TrajectoryEntity.getTrajectoryType("实线");
            } else if (position == 1) {
                rbLineType1.setText("双实线");
                rbLineType2.setText("双虚线");
                rbLineType3.setText("虚实线");
                setViewVisibility(llYellowDis, 1);
                rbYellow.setChecked(true);
            }
        } else if (position == 3 || position == 4 || position == 5 || position == 9) {
            if (position == 9) setViewVisibility(llLineWidth, 3);
            setViewVisibility(llLineColor, position == 9 ? 3 : 1);
            rbWhite.setChecked(true);
            setButtonBackground(btnPoint1, "采集点位1", 1);
            setButtonBackground(btnPoint2, "采集点位2", 1);
            setViewVisibility(btnAction1, 3);
            setButtonBackground(btnAction2, "删除当前轨迹", 2);
            if (position == 3 || position == 9) {
                if (position == 3) etLineWidth.setText("30");
                setViewVisibility(llTwoRow, 1);
                setButtonBackground(btnPoint3, "采集点位3", 1);
                if (position == 9) {
                    setViewVisibility(btnPoint4, 2);
                } else {
                    setButtonBackground(btnPoint4, "采集点位4", 1);
                }
            } else if (position == 4) {
                etLineWidth.setText("30");
            } else if (position == 5) {
                setViewVisibility(llLineWidth, 3);
            }
        } else if (position == 6) {
            currentTrajectory = null;
            setViewVisibility(llLineColor, 3);
            setViewVisibility(llOneRow, 3);
            setViewVisibility(lvRoadMark, 1);
            etLineWidth.setText("25");
            setButtonBackground(btnAction1, "+新增采集标识", 1);
            btnAction2.setText("删除上一个路标");
            roadMarks.clear();
            roadMarkAdapter = new RoadMarkAdapter(this, roadMarks, this);
            lvRoadMark.setAdapter(roadMarkAdapter);
        } else if (position == 7 || position == 8) {
            setViewVisibility(llLineColor, 1);
            rbWhite.setChecked(true);
            etLineWidth.setText("15");
            setButtonBackground(btnPoint1, "采集点位", 1);
            setViewVisibility(btnPoint2, 3);
            setButtonBackground(btnAction1, "删除上一点位", 2);
            setButtonBackground(btnAction2, "删除当前轨迹", 2);
        }
    }

    /**
     * 初始化多车道采集布局
     */
    protected void initMultiLane() {
        setButtonBackground(btnAction1, "校准当前轨迹（最新采集的一个点）", 1);
        setViewVisibility(llWidthColor, 3);
        setViewVisibility(llChooseTraject, 3);
        setViewVisibility(llChoosePoints, 3);
        setViewVisibility(llOneRow, 3);
        setViewVisibility(btnAction2, 3);
        setViewVisibility(tvSaveTrajectory, 1);
        tvSaveTrajectory.setText("保存轨迹");
        List<String> lanes = new ArrayList<>();
        for (int i = 0; i < 7; i++) {
            lanes.add(i + "");
        }
        setSpinnerAdapter(lanes, spLaneCount);
    }

    /**
     * 设置控件的显示与隐藏状态
     */
    private void setViewVisibility(View view, int type) {
        if (type == 1 && view.getVisibility() != View.VISIBLE) {
            view.setVisibility(View.VISIBLE);
        }
        if (type == 2 && view.getVisibility() != View.INVISIBLE) {
            view.setVisibility(View.INVISIBLE);
        }
        if (type == 3 && view.getVisibility() != View.GONE) {
            view.setVisibility(View.GONE);
        }
    }

    /**
     * 设置按钮背景为色
     */
    private void setButtonBackground(Button button, String text, int type) {
        setViewVisibility(button, 1);
        button.setText(text);
        if (type == 1) {
            button.setBackgroundResource(R.drawable.item_traject_blue_selector);
            button.setTextColor(Color.WHITE);
        } else {
            button.setBackgroundResource(R.drawable.item_traject_white_selector);
            if (type == 2) {
                button.setTextColor(getResources().getColor(R.color.red1));
            } else {
                button.setTextColor(getResources().getColor(R.color.main_gray));
            }
        }
    }

    /**
     * 设置spinner的适配器
     */
    public void setSpinnerAdapter(List<String> lines, Spinner spLineNumber) {
        ArrayAdapter<String> deviceNameAdapter = new ArrayAdapter<String>(this, R.layout.item_spinner, lines);
        deviceNameAdapter.setDropDownViewResource(R.layout.item_spinner_dropdown);
        spLineNumber.setAdapter(deviceNameAdapter);
    }


    /**
     * 判断是否高精度
     *
     * @return
     */
    protected boolean noEnoughAccuracy() {
        if (!G.isExploitation) {
            if (null == gpsInfo || gpsInfo.getStatusPosition() != 3) {
                MessageBox.show(this, "当前定位精度不够！");
                return true;
            }
        }
        return false;
    }

    /**
     * 采集点位
     * index
     */
    protected void doCollectPoint(int index) {
        setGpsInfo();
        TrajectoryPointEntity trajectoryPoint = new TrajectoryPointEntity();
        trajectoryPoint.setTrajectory(currentTrajectory);
        trajectoryPoint.setTrajectoryId(currentTrajectory.getId());
        trajectoryPoint.setPoint(presenter.setTrajectoryPoint(gpsInfo));
        if (currentTrajectory.getTrajectoryType() == 9 || currentTrajectory.getTrajectoryType() == 19 || currentTrajectory.getTrajectoryType() == 20) {
            //双黄线
            trajectoryPoint.setOrderIndex("1" + (mapView.trajectoryPoints.size() + 1));
        } else {
            trajectoryPoint.setOrderIndex((mapView.trajectoryPoints.size() + 1) + "");
        }
        if (presenter.saveTrajectoryPoint(trajectoryPoint, 1)) {
            mapView.trajectoryPoints.add(trajectoryPoint);
            switch (index) {
                case 1:
                    if (position == 0 || position == 1) {
                        btnPoint1.setText("采点" + (mapView.trajectoryPoints.size() + 1));
                    } else if (position == 7 || position == 8) {
                        btnPoint1.setText("采集点位" + (mapView.trajectoryPoints.size() + 1));
                        if (mapView.trajectoryPoints.size() >= 4) {
                            updateTrajectory();
                        }
                    } else if (position == 3 || position == 4 || position == 5 || position == 9) {
                        setButtonBackground(btnPoint1, "校准点位" + index, 3);
                    }
                    break;
                case 2:
                    setButtonBackground(btnPoint2, "校准点位" + index, 3);
                    if (position == 4 || position == 5) {
                        updateTrajectory();
                        mapView.setCollect(false);
                    }
                    break;
                case 3:
                    if (position == 0 || position == 1) {
                        updateTrajectory();
                        if (isAutoCollect) {
                            isAutoCollect = false;
                            btnPoint4.setText("开始自动采集");
                            lastAutoCollectPoint = null;
                        }
                        mapView.setCollect(false);
                        btnPoint1.setText("采点1");
//                        setLineTypeRadioButton(true);
                    } else if (position == 3 || position == 9) {
                        setButtonBackground(btnPoint3, "校准点位" + index, 3);
                        if (position == 9) {   //刹车区域采集完3个点，自动生成第四个点，并保存轨迹
                            PointBean point4 = jtsUtils.getPoint4ByFront3(mapView.trajectoryPoints.get(0).getPoint(), mapView.trajectoryPoints.get(1).getPoint(), mapView.trajectoryPoints.get(2).getPoint(), stationParamConfig.isBaseCalibration() && StringUtils.isNotEmpty(stationParamConfig.getBaseStationLocation()));
                            trajectoryPoint = new TrajectoryPointEntity();
                            trajectoryPoint.setTrajectory(currentTrajectory);
                            trajectoryPoint.setTrajectoryId(currentTrajectory.getId());
                            trajectoryPoint.setPoint(point4);
                            trajectoryPoint.setOrderIndex((mapView.trajectoryPoints.size() + 1) + "");
                            if (presenter.saveTrajectoryPoint(trajectoryPoint, 1)) {
                                mapView.trajectoryPoints.add(trajectoryPoint);
                                mapView.setCollect(false);
                            }
                        }
                    }
                    break;
                case 4:
                    setButtonBackground(btnPoint4, "校准点位" + index, 3);
                    updateTrajectory();
                    mapView.setCollect(false);
                    break;
            }
        }
    }

    /**
     * 初始化参数
     */
    private void initContent() {
        currentMarkPosition = -1;
        changePosition = -1;
        position = -1;
        mapView.setCollect(false);
        isAutoCollect = false;
        mapView.setCurrentUpdateTrajectory(null);
        mapView.setCurrentUpdatePoint(null);
        presenter.initTrajectoryPoints(mapView);
        currentTrajectory = null;
        tvProjectName.setText("请选择操作的轨迹");
        btnChooseTraject.setText("");
        btnChoosePoints.setText("");
        tvChangeTraject.setText("修改保存");
        etLineWidth.setText("15");
        setViewVisibility(rlScqy, 3);
        setViewVisibility(tvPointDis, 3);
        setViewVisibility(ivSelectTraject, 3);
        setViewVisibility(llMultiLane, 3);
        setViewVisibility(llLineType, 3);
        setViewVisibility(llLineWidth, 1);
        setViewVisibility(llYellowDis, 3);
        setViewVisibility(llLineColor, 1);
        rbWhite.setChecked(true);
        setViewVisibility(llCollectDir, 3);
        setViewVisibility(llChooseTraject, 1);
        setViewVisibility(llChoosePoints, 1);
        setViewVisibility(llOneRow, 1);
        setViewVisibility(llTwoRow, 3);
        setButtonBackground(btnPoint1, "删除点位", 2);
        setButtonBackground(btnPoint2, "校准点位", 3);
        setViewVisibility(lvRoadMark, 3);
        setViewVisibility(btnAction1, 3);
        setButtonBackground(btnAction2, "删除当前轨迹", 2);
        setViewVisibility(tvSaveTrajectory, 1);
        tvSaveTrajectory.setText("采集轨迹");
    }

    /**
     * 保存轨迹
     */
    private void updateTrajectory() {
        //采集下个轨迹时  修改当前轨迹参数
        boolean isUpdate = false;
        if (llLineWidth.getVisibility() == View.VISIBLE) {
            String lineWidth = etLineWidth.getText().toString().trim();
            if ("".equals(lineWidth)) {
                if (position == 4) {  //停止线
                    lineWidth = "30";
                } else if (position == 6) { //道路标识
                    lineWidth = "25";
                } else {
                    lineWidth = "15";
                }
            }
            if (currentTrajectory.getLineWidth() != Integer.parseInt(lineWidth)) {
                isUpdate = true;
                currentTrajectory.setLineWidth(Integer.parseInt(lineWidth));
            }
        }
        if (llLineColor.getVisibility() == View.VISIBLE) {
            int color = ((RadioButton) rgLineColor.getChildAt(0)).isChecked() ? 1 : 2;
            if (currentTrajectory.getLineColor() != color) {
                isUpdate = true;
                currentTrajectory.setLineColor(color);
            }
        }
        if (llCollectDir.getVisibility() == View.VISIBLE) {
            int direction = ((RadioButton) rgCollectDir.getChildAt(0)).isChecked() ? 1 : 2;
            if (currentTrajectory.getCollectDirection() != direction) {
                isUpdate = true;
                currentTrajectory.setCollectDirection(direction);
            }
        }
        if (isUpdate) {
            presenter.updateTrajectory(currentTrajectory);
        }
        //双黄线采集时生成左侧实线点位  采集轨迹时才调用，修改不调用
        if (currentTrajectory.getTrajectoryType() == 9 || currentTrajectory.getTrajectoryType() == 19 || currentTrajectory.getTrajectoryType() == 20) {
            LoadDialog.show(this, "正在保存，请稍后...", false);
            String distance = etYellowDis.getText().toString().trim();
            float jjValue; //双簧线偏移距离
            if (currentTrajectory.getCollectDirection() == 1) {
                jjValue = -(Float.parseFloat("".equals(distance) ? "35" : distance) + currentTrajectory.getLineWidth()) / 100.0f;
            } else {
                jjValue = (Float.parseFloat("".equals(distance) ? "35" : distance) + currentTrajectory.getLineWidth()) / 100.0f;
            }
            new Thread(() -> {
                //保存双黄线左侧实线点位
                presenter.saveSHXLeftPoint(mapView.trajectoryPoints, jjValue);
                runOnUiThread(() -> LoadDialog.dismiss(this));
            }).start();
        }

    }

    /**
     * 修改轨迹保存
     */
    protected void changeTrajectory(int type) {
        if (llLineWidth.getVisibility() == View.VISIBLE) {
            int lineWidth = Integer.parseInt(etLineWidth.getText().toString().trim());
            if (currentTrajectory.getLineWidth() != lineWidth) {
                currentTrajectory.setLineWidth(lineWidth);
            }
        }
        if (llLineColor.getVisibility() == View.VISIBLE) {
            int color = ((RadioButton) rgLineColor.getChildAt(0)).isChecked() ? 1 : 2;
            if (currentTrajectory.getLineColor() != color) {
                currentTrajectory.setLineColor(color);
            }
        }
        if (presenter.updateTrajectory(currentTrajectory)) {
            MessageBox.show(this, "修改成功！");
        }
        if (type == 2) {
            initContent();
        }
    }

    /**
     * 由于刹车区域4点是由前面三个点生成的，所以校准前面三个点的时候，第4点也会跟着变化
     */
    private int setScqyPoint4() {
        int count = 0;
        if (position == 9 && mapView.trajectoryPoints.size() == 4) {
            List<TrajectoryPointEntity> points = mapView.trajectoryPoints;
            PointBean point4 = jtsUtils.getPoint4ByFront3(points.get(0).getPoint(), points.get(1).getPoint(), points.get(2).getPoint(), stationParamConfig.isBaseCalibration() && StringUtils.isNotEmpty(stationParamConfig.getBaseStationLocation()));
            TrajectoryPointEntity tp = points.get(3);
            tp.setTrajectory(currentTrajectory);
            tp.setTrajectoryId(currentTrajectory.getId());
            tp.setPoint(point4);
            if (presenter.saveTrajectoryPoint(tp, 2)) ;
            count = 1;
        }
        return count;
    }

    /**********多车道适配器点击事件回调***********/
    @Override
    public void onAddChild(int position) {
        if (null == mapView.laneLists) return;
        TrajectoryEntity trajectory = presenter.saveTrajectory(1, true);
        if (null != trajectory) {
            mapView.laneLists.get(position).setAdd(false);
            mapView.laneLists.get(position).setDelete(false);
            mapView.laneLists.add(position + 1, presenter.setMultiLaneModel(mapView, trajectory, position));
            multiLaneAdapter.notifyDataSetChanged();
        } else {
            MessageBox.show(this, "添加失败，请重试！");
        }
    }

    @Override
    public void onDeleteChild(int position) {
        if (null == mapView.laneLists) return;
        mapView.laneLists.get(position - 1).setAdd(true);
        if (mapView.laneLists.get(position - 1).isShowNumber()) {
            mapView.laneLists.get(position - 1).setDelete(false);
        } else {
            mapView.laneLists.get(position - 1).setDelete(true);
        }
        if (presenter.deleteTrajectory(mapView.laneLists.get(position).getTrajectory())) {
            mapView.laneLists.remove(position);
            multiLaneAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onCollectPoint(int position) {
        if (null == mapView.laneLists) return;
        //多车道采集
        if (noEnoughAccuracy()) return;
        if (!mapView.isCollect()) {
            mapView.setCollect(true);
        }
        changePosition = position;
        MultiLaneModel multiLaneModel = mapView.laneLists.get(position);
        TrajectoryEntity trajectory = multiLaneModel.getTrajectory();
        List<TrajectoryPointEntity> points = multiLaneModel.getTrajectoryPoints();
        TrajectoryPointEntity trajectoryPoint = new TrajectoryPointEntity();
        trajectoryPoint.setPoint(presenter.setTrajectoryPoint(gpsInfo));
        trajectoryPoint.setTrajectory(trajectory);
        trajectoryPoint.setTrajectoryId(trajectory.getId());
        if (trajectory.getTrajectoryType() == 9 || trajectory.getTrajectoryType() == 19 || trajectory.getTrajectoryType() == 20) {
            trajectoryPoint.setOrderIndex("1" + (points.size() + 1));
        } else {
            trajectoryPoint.setOrderIndex((points.size() + 1) + "");
        }
        if (presenter.saveTrajectoryPoint(trajectoryPoint, 1)) {
            points.add(trajectoryPoint);
            multiLaneModel.setTrajectoryPoints(points);
            mapView.laneLists.set(position, multiLaneModel);
            multiLaneAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onCollectEnd(int position) {
        if (null == mapView.laneLists) return;
        changePosition = position;
        if (noEnoughAccuracy()) return;
        MultiLaneModel multiLaneModel = mapView.laneLists.get(position);
        TrajectoryEntity trajectory = multiLaneModel.getTrajectory();
        List<TrajectoryPointEntity> points = multiLaneModel.getTrajectoryPoints();
        if (points.size() == 0) {
            MessageBox.show(this, "当前线段点位小于一个，不能采集结束点！");
            return;
        }
        TrajectoryPointEntity trajectoryPoint = new TrajectoryPointEntity();
        trajectoryPoint.setPoint(presenter.setTrajectoryPoint(gpsInfo));
        trajectoryPoint.setTrajectory(trajectory);
        trajectoryPoint.setTrajectoryId(trajectory.getId());
        if (trajectory.getTrajectoryType() == 9 || trajectory.getTrajectoryType() == 19 || trajectory.getTrajectoryType() == 20) {
            trajectoryPoint.setOrderIndex("1" + (points.size() + 1));
        } else {
            trajectoryPoint.setOrderIndex((points.size() + 1) + "");
        }
        if (presenter.saveTrajectoryPoint(trajectoryPoint, 1)) {
            points.add(trajectoryPoint);
            multiLaneModel.setCollectEnd(true);
            multiLaneModel.setTrajectoryPoints(points);
            mapView.laneLists.set(position, multiLaneModel);
            multiLaneAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onStyleChange(int position) {
        if (null == mapView.laneLists) return;
        MultiLaneModel multiLaneModel = mapView.laneLists.get(position);
        TrajectoryEntity trajectory = multiLaneModel.getTrajectory();
        switch (multiLaneModel.getLineType()) {
            case 1:
                trajectory.setTrajectoryType(1);
                break;
            case 2:
                trajectory.setTrajectoryType(2);
                break;
            case 3:
                trajectory.setTrajectoryType(7);
                break;
            case 4:
                trajectory.setTrajectoryType(9);
                break;
            case 5:
                trajectory.setTrajectoryType(19);
                break;
            case 6:
                trajectory.setTrajectoryType(20);
                break;
        }
        trajectory.setLineWidth(multiLaneModel.getLineWidth());
        trajectory.setLineColor(multiLaneModel.getLineColor());
        presenter.updateTrajectory(trajectory);
    }

    /************道路标识适配器点击事件回调********************/
    /**
     * 道路标识采集点位点击事件
     * markType 标识类型
     * position  listView中item的位置
     * action 修改道路标识   1：点位1   2：点位2
     */
    @Override
    public void onMarkCollectClick(int markType, int position, int action) {
        if (noEnoughAccuracy()) return;
        switch (action) {
            case 0:  //点击道路标识，更换标识类型
                showChangeRoadMarkDialog(markType, position);
                break;
            case 1:
                if (roadMarks.get(position).getPoint1Type() == 1) {
                    if (mapView.trajectoryPoints.size() == 1) {
                        MessageBox.show(this, "请先采集完上个标识！");
                        return;
                    } else {
                        if (currentMarkPosition != -1) {
                            roadMarks.get(currentMarkPosition).setPoint1Type(3);
                            roadMarks.get(currentMarkPosition).setPoint2Type(3);
                            roadMarkAdapter.notifyDataSetChanged();
                        }
                        currentMarkPosition = position;
                        mapView.trajectoryPoints = new ArrayList<>();
                        mapView.setCollect(true);
                    }
                }
                break;
            case 2:
                if (mapView.trajectoryPoints.size() == 0) {
                    MessageBox.show(this, "请先采集点1");
                    return;
                }
                break;
        }
        if (action == 1) {  //点1
            mapView.collectType = roadMarks.get(position).getMarkType();
            if (roadMarks.get(position).getPoint1Type() == 1) { //采集
                collectPointRoadMark(position, action);
            } else {  //校准
                if (mapView.trajectoryPoints.size() == 0) {
                    //有时候出现采集了点1，mapView.trajectoryPoints.size()仍然为0，这里再采集一下
                    collectPointRoadMark(position, action);
                } else {
                    presenter.calibrationTrajectoryPoint(mapView.trajectoryPoints.get(0), gpsInfo);
                }
            }
        } else if (action == 2) {  //点2
            if (roadMarks.get(position).getPoint2Type() == 1) { //采集
                if (currentMarkPosition != position) {
                    MessageBox.show(this, "请先采集完上个标识！");
                    return;
                }
                TrajectoryPointEntity trajectoryPoint = new TrajectoryPointEntity();
                trajectoryPoint.setTrajectory(roadMarks.get(position).getTrajectory());
                trajectoryPoint.setTrajectoryId(roadMarks.get(position).getTrajectory().getId());
                trajectoryPoint.setPoint(presenter.setTrajectoryPoint(gpsInfo));
                trajectoryPoint.setOrderIndex(position + "" + action + "");
                if (presenter.saveTrajectoryPoint(trajectoryPoint, 1)) {
                    mapView.trajectoryPoints.add(trajectoryPoint);
                    roadMarks.get(position).setPoint2Type(2);
                }
            } else {
                presenter.calibrationTrajectoryPoint(mapView.trajectoryPoints.get(1), gpsInfo);
            }
        }
        roadMarkAdapter.notifyDataSetChanged();
        if (mapView.trajectoryPoints.size() == 2) {
            mapView.setCollect(false);
        }
    }

    /**
     * 道路标识采集点位
     *
     * @param position
     * @param action
     */
    private void collectPointRoadMark(int position, int action) {
        TrajectoryPointEntity trajectoryPoint = new TrajectoryPointEntity();
        trajectoryPoint.setTrajectory(roadMarks.get(position).getTrajectory());
        trajectoryPoint.setTrajectoryId(roadMarks.get(position).getTrajectory().getId());
        trajectoryPoint.setPoint(presenter.setTrajectoryPoint(gpsInfo));
        trajectoryPoint.setOrderIndex(position + "" + action + "");
        if (presenter.saveTrajectoryPoint(trajectoryPoint, 1)) {
            mapView.trajectoryPoints.add(trajectoryPoint);
            roadMarks.get(position).setPoint1Type(2);
        }
    }

    /**
     * 道路标识添加或删除
     *
     * @param type 1：添加  2：删除
     */
    @Override
    public void onRoadMarkAction(int type, int position) {
        if (type == 1) {
            markSelectList.add(roadMarkList.get(position));
        } else {
            markSelectList.remove(position);
        }
        selectRoadMarkAdapter.notifyDataSetChanged();
        //在setSelection的时候，主线程可能在做其他操作，导致setSelection失效。加一个线程解决问题
        if (markSelectList.size() > 0) {
            GridViewUtil.setGridViewHeightByChildren(this, gvSelectMark, 180);
            new Handler().post(() -> gvSelectMark.setSelection(markSelectList.size() - 1));
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (null != mapView && mapView.isCollect()) {
                MessageBox.show(this, "当前轨迹尚未采集结束！");
                return true;
            }
            finish();
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        isAutoCollect = false;
        handler.removeCallbacks(stateInfoRunnable);
        if (mapView != null) mapView.destroy();
        super.onDestroy();
    }


    private int times = 0;

    private void setGpsInfo() {
        if (G.isExploitation) {
            if (times == 0) {
                setLocation(-60f, -50f);
            } else if (times == 1) {
                setLocation(-62f, -52f);
            } else if (times == 2) {
                setLocation(-64f, -54f);
            } else if (times == 3) {
                setLocation(-66f, -56f);
            } else if (times == 4) {
                setLocation(-68f, -58f);
            }
            times++;
        }
    }

    private void setLocation(float distanceX, float distanceY) {
        gpsInfo.setDistanceX(distanceX);
        gpsInfo.setDistanceY(distanceY);
        if (true) {
            String[] baseLocations = stationParamConfig.getBaseStationLocation().split(",");
            double longitude = Double.parseDouble(baseLocations[0]);
            double latitude = Double.parseDouble(baseLocations[1]);
            gpsInfo.setLongitude(GpsUtil.getCurLongitude(longitude, latitude, distanceX));
            gpsInfo.setLatitude(GpsUtil.getCurLatitude(latitude, distanceY));
        }
    }

}